#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/08/01 15:32:08
'''
import sys
sys.path.append(".")
from Common.Utils import Utils
from db_logic.db_base import Repository
from models.power_models import EntityModuleRelation


class BllModuleRelation(Repository):

    def __init__(self, entityType=EntityModuleRelation):
        return super().__init__(entityType)


    def get_login_user_module_list(self, user_id, role_id):
        # sql_all = f"""
        # select c.module_id, c.module_code, c.sort_index, c.module_name, c.module_type from(

        #     SELECT a.module_id, b.module_code, b.sort_index, b.module_name, b.module_type
        #         from rms_module_relation as a 
        #             LEFT JOIN rms_module as b on a.module_id=b.module_id 
        #                 WHERE object_id='{user_id}' AND object_type=2 AND b.module_type!=1
        #     UNION
        #         SELECT a.module_id, b.module_code, b.sort_index, b.module_name, b.module_type
        #             from rms_module_relation as a 
        #                 LEFT JOIN rms_module as b on a.module_id=b.module_id 
        #                     WHERE object_id='{role_id}' AND object_type=1 AND b.module_type!=1
        #     ) c ORDER BY c.sort_index asc
        # """
        # sql_data = self.execute(sql_all).fetchall()
        # data = Utils.msyql_table_model(sql_data)
        # data_dict = {
        #     "client_manage": [],
        #     "drug_manage": [],
        #     "standard_manage": [],
        #     "consumables_manage": [],
        #     "instrument_manage": []
        # }
        # for i in data:
        #     if i["module_type"] == "1":
        #         data_dict["client_manage"].append(i)
        #     elif i["module_type"] == "2":
        #         data_dict["drug_manage"].append(i)
        #     elif i["module_type"] == "3":
        #         data_dict["standard_manage"].append(i)
        #     elif i["module_type"] == "4":
        #         data_dict["consumables_manage"].append(i)
        #     elif i["module_type"] == "5":
        #         data_dict["instrument_manage"].append(i)

        # return data_dict
        # # return self.execute(sql_all).fetchall()
        sql_all = f"""
        select c.module_id, c.module_code, c.sort_index, c.module_name, c.module_type from(

            SELECT a.module_id, b.module_code, b.sort_index, b.module_name, b.module_type
                from rms_module_relation as a 
                    LEFT JOIN rms_module as b on a.module_id=b.module_id 
                        WHERE object_id='{user_id}' AND object_type=2
            UNION
                SELECT a.module_id, b.module_code, b.sort_index, b.module_name, b.module_type
                    from rms_module_relation as a 
                        LEFT JOIN rms_module as b on a.module_id=b.module_id 
                            WHERE object_id='{role_id}' AND object_type=1
            ) c ORDER BY c.sort_index asc
        """
        sql_data = self.execute(sql_all).fetchall()
        data = Utils.msyql_table_model(sql_data)
        data_dict = {
            "client_manage":[],
            "drug_manage": [],
            "standard_manage": [],
            "consumables_manage": [],
            "instrument_manage": [],
        }
        for i in data:
            if i["module_type"] == "1":
                data_dict["client_manage"].append(i)
            elif i["module_type"] == "2":
                data_dict["drug_manage"].append(i)
            elif i["module_type"] == "3":
                data_dict["standard_manage"].append(i)
            elif i["module_type"] == "4":
                data_dict["consumables_manage"].append(i)
            elif i["module_type"] == "5":
                data_dict["instrument_manage"].append(i)

        return data_dict
    
    def get_user_manage_auth(self, user_info):
        sql_all = f"""
        select module_code from (
            select module_id, object_id from rms_module_relation where module_type=2 and (object_id='{user_info.user_id}' or object_id='{user_info.role_id}')
        )as a LEFT JOIN (
            select module_id, module_code from rms_module
        )as b on a.module_id = b.module_id
        """
        data = self.execute(sql_all).fetchall()
        data_list = [i.module_code for i in data]
        return data_list

    
    def get_user_module_list(self, user_info):
        sql_all = f"""
            select a.module_id, a.module_name, a.module_type, a.module_code, a.sort_index,  
            CASE WHEN b.object_id is NULL THEN 0 ELSE 1 END have, IFNULL(b.object_type,0) object_type
             from (
	               select * from rms_module) a LEFT JOIN (
		                 select * from rms_module_relation where object_id='{user_info.user_id}' or object_id='{user_info.role_id}'
                  ) b on a.module_id = b.module_id
        """
        sql_data = self.execute(sql_all).fetchall()
        data = Utils.msyql_table_model(sql_data)
        data_dict = {
            "client_manage":[],
            "drug_manage": [],
            "standard_manage": [],
            "consumables_manage": [],
            "instrument_manage": [],
        }
        for i in data:
            if i["module_type"] == "1":
                data_dict["client_manage"].append(i)
            elif i["module_type"] == "2":
                data_dict["drug_manage"].append(i)
            elif i["module_type"] == "3":
                data_dict["standard_manage"].append(i)
            elif i["module_type"] == "4":
                data_dict["consumables_manage"].append(i)
            elif i["module_type"] == "5":
                data_dict["instrument_manage"].append(i)
        return data_dict
    
    
    def get_role_module_list(self, role_id):
        sql_all = f"""
        select a.module_id, a.module_code, a.sort_index, a.module_name, a.module_type,
	        CASE WHEN b.object_id is NULL THEN 0 ELSE 1 END have from rms_module as a LEFT JOIN (
	            select * from rms_module_relation WHERE object_id='{role_id}' and object_type=1
	        ) b on a.module_id=b.module_id
        """
        return self.execute(sql_all).fetchall()
    
    def get_role_name_list(self):
        return self.execute("select role_id, role_name from rms_role").fetchall()
    
    def get_role_module(self, page_param):
        sql_all = """
        select 
            a.role_id,
            a.role_name, 
            a.role_code, 
            a.description,
            group_concat(c.module_name) module_name 
        from rms_role as a 
            LEFT JOIN rms_module_relation as b 
                on b.object_id=a.role_id 
            LEFT JOIN rms_module as c 
                on c.module_id=b.module_id
                GROUP BY role_id
        """
        try:
            count_number = len(self.execute(sql_all).fetchall())
        except Exception:
            count_number = 0
        page_param.totalRecords=count_number
        page_sql_data = Utils.sql_paging_assemble(sql_all, page_param)

        return self.execute(page_sql_data).fetchall()
    
    def add_inster_user_moduele(self):
        role_id = "19535c92-8da4-4645-88c5-9a4ee3fdb22e"
        obj_list = []
        all_module_list = self.execute("select * from rms_module")
        all_module_list = Utils.msyql_table_model(all_module_list)
        for i in all_module_list:
            obj = EntityModuleRelation(
                object_type=1,
                object_id=role_id,
                module_type=i['module_type'],
                module_id=i['module_id'],
                create_date=Utils.get_str_datetime(),
                create_user_id='',
                create_user_name=''
            )
            obj_list.append(obj)
        self.insert_many(obj_list)



if __name__ == '__main__':
    module_list = BllModuleRelation().add_inster_user_moduele()
    # module_list = Utils.msyql_table_model(module_list)
    # if len(module_list) > 6:
    #     for module in module_list:
    #         if module["module_code"] == "DataReport":
    #             if module_list.index(module) in [1,2,4]:
    #                 module_list.pop(module_list.index(module))
    #                 module_list.insert(5, module)
    # data = module_list
    # for i in data:
    #     print(data)

